<?php
/**
 * 小程序登录
 */
namespace App\Http\Controllers\Api\V1\Base;

use App\Http\Controllers\Api\V1\BaseController;

use App\Models\Base\Member;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

use Log;

class MiniProgramLoginController extends BaseController
{

    /**
     * @api {post} /minicode  小程序微信代码返回
     * @apiDescription 通过code 获取openid session_key
     * @apiGroup Wechat
     * @apiPermission
     * @apiVersion 1.0.0
     * @apiParam {String} code  微信端获取到的code
     * @apiSuccess {string} token  token
     * @apiSuccess {string} phone  是否绑定 0 未绑定 1 已绑定
     * @apiSuccess {string} status  审核是否通过:0.未提交1.审核中2.通过3.拒绝' 为0时需要补充资料，1，2 是正常状态，3是拒绝状态
     * @apiSuccess {string} expired_at  过期时间
     * @apiSuccess {string} refresh_expired_at  刷新时间
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 200 OK
    {
    "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vYmFzZS53ZWl5aW5namlhLm9yZy9hcGkvYmFzZS9taW5pY29kZSIsImlhdCI6MTUzMjQwMTAyMCwiZXhwIjoxNTMyNDA0NjIwLCJuYmYiOjE1MzI0MDEwMjAsImp0aSI6Imh6ejVjVWNPNndPckNFeFEiLCJzdWIiOjIsInBydiI6ImE3ZDY0N2NhZGFhOGZhM2U4YmRlMGI1Yjg2ZjU3ZDE0YjAzYTA1ZDYifQ.OzCIRLI0eDuG7yiE8--XpBrq69ehnh3zSChTUhSdUsk",
    "phone": 0,
    "status": 0,
    "expired_at": "2018-07-24 11:57:00",
    "refresh_expired_at": "2018-08-07 10:57:00"
    }
    }
     * @apiErrorExample {json} Error-Response:
    HTTP/1.1 400
     *{
    "message": "code 无效",
    "status_code": 400,
     * }
     */
    public function getOpenid (Request $request)
    {
        $validator = Validator::make($request->input(),[
            'code' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }

        $appid  = env('MINI_APPID');
        $secret  = env('MINI_SECRET');
        $code = $request->input('code');
        //log::info($code.'==$code');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        //log::info($url.'==$url');
        $result = $this->httpGet($url);
        Log::info(json_encode($result));
        if (env('APP_ENV') == 'local') {
            //       错误日志  {"errcode":40163,"errmsg":"code been used, hints: [ req_id: Vuw2nA0400th57 ]"}
            $result = '{"openid":20000,"errmsg":"invalid code, hints: [ req_id: AQZ1ba0584th47 ]"}';
            Log::info($result);

            $result = json_decode($result, true);
        }
        if(!isset($result['openid'])){
            return $this->response->errorBadRequest('code 无效');
        }

        $user = Member::where('mini_openid', $result["openid"])->first(); //select("id", "openid", "phone","password")->
        Log::info($user);
        if (empty($user)) { //新增
            $attributes = array();
            $attributes["mini_openid"] = $result["openid"];
            $attributes["password"] = app('hash')->make('111111');

            $user =  Member::create($attributes);
            $user->info()->create(array('member_id'=>$user->id));
        }
        else
        {
            //更新最后登录时间
            $user->updated_at = Carbon::now();
//            $request->setTrustedProxies(array('10.32.0.1/16'));
            $ip = $request->getClientIp();
            Log::info('ip == '.$ip);
            $user->login_ip = ip2long($ip);

            $user->save();
        }

        if (!$token = Auth::login($user)) {
            $this->response->errorForbidden(trans('auth.incorrect'));
        }

        $phone = 0;
        if(!empty($user->phone))
        {
            $phone = 1;
        }
        Log::info($user);

        $return['data'] = [
          'token' => $token,
          'phone' => $phone,
          'status'=>$user->audit,
          'expired_at' => Carbon::now()->addMinutes(config('jwt.ttl'))->toDateTimeString(),
          'refresh_expired_at' => Carbon::now()->addMinutes(config('jwt.refresh_ttl'))->toDateTimeString(),
        ];

        return $this->response->array($return)->setStatusCode(201);

//        return $result;
    }


}